﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Editing;

namespace TapiocaWpf.Views
{
    /// <summary>
    /// Interaction logic for FindAndReplaceWindow.xaml
    /// </summary>
    public partial class FindAndReplaceWindow : Window
    {
        public FindAndReplaceWindow()
        {
            InitializeComponent();
        }

        private void btnFindNext_Click(object sender, RoutedEventArgs e)
        {
            TextEditor textEditor = ((MainWindow)this.Owner).textEditor;
            
            string searchText = this.search.Text;
            string csText = textEditor.Text; 
            int nIndex = csText.IndexOf(searchText);
            TextArea area = textEditor.TextArea;
            int nLineNumber = area.Document.GetLineByOffset(nIndex).LineNumber;
            textEditor.Select(nIndex, searchText.Length);
            textEditor.ScrollTo(nLineNumber,1);

            //textEditor.Document.GetLocation(nIndex);
        }


        private void btnReplace_Click(object sender, RoutedEventArgs e)
        {
            TextEditor textEditor = ((MainWindow)this.Owner).textEditor;
            string searchText = this.search.Text;
            string replaceText = this.replace.Text;
            string contentText = textEditor.Text;

            int nIndex = contentText.IndexOf(searchText);
            TextArea area = textEditor.TextArea;
            int nLineNumber = area.Document.GetLineByOffset(nIndex).LineNumber;
            textEditor.Select(nIndex, searchText.Length);
            textEditor.ScrollTo(nLineNumber, 1);
            textEditor.Document.Replace(nIndex, this.search.Text.Length, this.replace.Text);
        }


        private void btnReplaceAll_Click(object sender, RoutedEventArgs e)
        {
            TextEditor textEditor = ((MainWindow)this.Owner).textEditor;
            string searchText = this.search.Text;
            string replaceText = this.replace.Text;
            string contentText = textEditor.Text;

            int nIndex = contentText.IndexOf(searchText);
            TextArea area = textEditor.TextArea;
            int nLineNumber = area.Document.GetLineByOffset(nIndex).LineNumber;
            textEditor.Select(nIndex, searchText.Length);
            textEditor.ScrollTo(nLineNumber, 1);
            contentText = contentText.Replace(searchText, replaceText);
            textEditor.Document.Text = contentText;
            //textEditor.Text = contentText;
        }

       
    }
}
